package com.kevin.netty.server.protocol.binary.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.kevin.netty.protocol.binary.BasicMessage;
import com.kevin.netty.protocol.binary.util.BinaryMessageUtil;
import com.kevin.netty.server.basic.AbstractInboundHandler;
import com.kevin.netty.starter.annotation.NettyHandler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Slf4j
@Component
@ChannelHandler.Sharable
@NettyHandler(name = "binary", order = 2)
public class BinaryInboundHandler extends AbstractInboundHandler {

    @Resource
    private ObjectMapper objectMapper;

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) {
        ByteBuf bf = (ByteBuf) o;
        byte[] data = new byte[bf.readableBytes()];
        bf.readBytes(data);

        try {
            BasicMessage basicMessage = BinaryMessageUtil.deserializer(data);
            objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
            log.info("<<<<<< binaryInboundHandler 接收数据：{}", objectMapper.writeValueAsString(basicMessage));
        } catch (Exception e) {
            log.warn("hex : {}\nbyteArray : {}\nerror : {}", Arrays.toString(data), ByteBufUtil.hexDump(data), e.getMessage());
        }
    }

}
